package org.lites.dcimmodifier;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.exifinterface.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import org.apache.commons.io.FilenameUtils;

import java.io.IOException;
import java.util.*;

import static org.lites.dcimmodifier.Constants.MAXHEIGHT;
import static org.lites.dcimmodifier.Constants.MAXWIDTH;

//让我们的适配器继承自RecyclerView.Adapter<>，并指定泛型为我们适配器的类名.ViewHolder，
// ViewHolder继承自RecyclerView.ViewHolder，并实现每个继承要实现的方法
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener {
    private Context context;

    private String[] id;
    private String[] name;
    private String[] path;
    //声明一个这个接口的变量
    private onRecyclerViewItemClickListener mOnRecyclerViewItemClickListener=null;

    //构造函数，主要用于接受数据，方便我们在适配器中对数据操作
    public RecyclerViewAdapter(Context context) {
        this.context = context;
    }
    public RecyclerViewAdapter(Context context, int[] image) {
        this.context = context;
//        this.image = image;
    }
    public RecyclerViewAdapter(Context context, DrawRecyclerInfo drawRecyclerInfo) {
        this.context = context;
        this.id=drawRecyclerInfo.getId();
        this.name=drawRecyclerInfo.getName();
        this.path =drawRecyclerInfo.getPath();
    }

    //创建ViewHolder，我们需要在这个方法中给新建一个view对象，再初始化一个ViewHolder对象，将view对象传入
    //然后返回一个ViewHolder对象
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //创建一个view对象（通过布局填充器将布局文件转化为view对象）
        //View view = View.inflate(context, R.layout.waterfall_item, null);
        View view = View.inflate(context, R.layout.imagedetail, null);
        //初始化一个ViewHolder对象，传入view对象
        ViewHolder viewHolder = new ViewHolder(view);

        view.setOnClickListener(this);
        //将ViewHolder对象返回出去
        return viewHolder;
    }

    //绑定ViewHolder，我们需要在这个方法中给控件设置数据
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        //给ImageView控件设置数据
//        holder.mImageView.setImageResource(image[position]);

        //给每个itemview添加一个Tag,传递数据
        Map<String,String>tagmap=new HashMap<>();
//        tagmap.put("image",""+image[position]);
        tagmap.put("id",id[position]);
        tagmap.put("music",name[position]);
        tagmap.put("crop", path[position]);
        holder.itemView.setTag(tagmap);
        if(this.id.length==0){
            holder.mTextViewID.setText(String.valueOf(position + 1));
        }else{
            holder.mTextViewID.setText(this.id[position]);
        }
        if(this.id.length==0) {
            holder.mTextViewName.setText("未知名称");
        }else {
            holder.mTextViewName.setText(this.name[position]);
        }
        setMediaInfoUI(holder, path[position],name[position]);
    }

    //获取item的条目总数
    @Override
    public int getItemCount() {
        //直接返回图片数组的长度即可
        return id.length;
    }

    //将点击事件转移给外面的调用者
    @Override
    public void onClick(View v) {
//        if (mOnRecyclerViewItemClickListener != null) {
//            Map<String,String>tagmap= (Map<String, String>) v.getTag();
//            //通过v.getTag()接受数据
//            mOnRecyclerViewItemClickListener.onItemClick(v, new DrawRecyclerInfo(new String[]{tagmap.get("id")},new String[]{tagmap.get("music")},new String[]{tagmap.get("crop")}));
//        }

    }

    //我们自定义的ViewHolder类，继承自RecyclerView.ViewHolder
    public class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView mTextViewID;
        private final TextView mTextViewName;
        private final ImageView mImageView;
        /***************MINIPLAYER***************/
        private TextView picName, picTimeStamp;
        private ImageView picAlbum;
        private ImageButton picTypeImg;
        private String filePath;
        /*************MINIPLAYER_END*************/

        public ViewHolder(View itemView) {
            super(itemView);

            mTextViewID = (TextView) itemView.findViewById(R.id.labelID);
            mTextViewName = (TextView) itemView.findViewById(R.id.pokemonName);
            //通过传过来的view对象，我们来实例化控件
            mImageView = (ImageView) itemView.findViewById(R.id.details_img);

            picName = itemView.findViewById(R.id.song_title_mini);
            picTimeStamp = itemView.findViewById(R.id.song_artist_mini);
            picAlbum = itemView.findViewById(R.id.song_album_art_mini);
            picTypeImg =itemView.findViewById(R.id.play_button_mini);
        }
        public TextView getPicName() {
            return picName;
        }
        public TextView getPicTimeStamp() {
            return picTimeStamp;
        }
        public ImageView getPicAlbum() {
            return picAlbum;
        }
        public String getFilePath() {
            return filePath;
        }

    }

    //自定义一个监听的接口，里面包含itemclick的监听方法，主要用于拿数据，方便外部调用拿数据
    public interface onRecyclerViewItemClickListener{
        void onItemClick(View view,DrawRecyclerInfo drawRecyclerInfo);

    }
    private BitmapFactory.Options resizeOptions(BitmapFactory.Options options,int maxWidth, int maxHeight) {
        // 获取缩略图的宽高
        int width = options.outWidth;
        int height = options.outHeight;

        // 计算 inSampleSize
        int inSampleSize = 1;
        if (width > maxWidth || height > maxHeight) {
            int halfWidth = width / 2;
            int halfHeight = height / 2;

            while ((halfWidth / inSampleSize) >= maxWidth && (halfHeight / inSampleSize) >= maxHeight) {
                inSampleSize *= 2;
            }
        }
        inSampleSize *= 2;
        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        options.outWidth = width / inSampleSize;
        options.outHeight = height / inSampleSize;
        return options;
    }
    private Bitmap decodeSampledBitmapFromFile(String filePath, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取图片尺寸
        BitmapFactory.decodeFile(filePath, options);
        options=resizeOptions(options, maxWidth, maxHeight);
        return BitmapFactory.decodeFile(filePath, options);
    }
    private void setMediaInfoUI(ViewHolder holder, String crop_item, String defaultName){

            String photofilename = crop_item;
            holder.picName.setText(defaultName);//retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)

            holder.picTimeStamp.setText(ImageUtils.imageInfoGetter(photofilename));
            String photoType = FilenameUtils.getExtension(photofilename);
            Set<String> type_image_list = new HashSet<>(Arrays.asList(Constants.TYPE_IMAGE));
            Set<String> type_video_list = new HashSet<>(Arrays.asList(Constants.TYPE_VIDEO));
            Bitmap bitmap = null;
            if (type_image_list.contains(photoType)) {
                bitmap = decodeSampledBitmapFromFile(photofilename, MAXWIDTH, MAXHEIGHT);
                holder.picTypeImg.setImageResource(R.drawable.panel_picture_frame_bg_normal);
            }
            else if (type_video_list.contains(photoType)) {
                bitmap = ThumbnailUtils.createVideoThumbnail(photofilename, MediaStore.Video.Thumbnails.MINI_KIND);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.outWidth=bitmap.getWidth();
                options.outHeight=bitmap.getHeight();
                resizeOptions(options,MAXWIDTH, MAXHEIGHT);
                bitmap  =Bitmap.createScaledBitmap(bitmap, options.outWidth, options.outHeight, true);
                holder.picTypeImg.setImageResource(R.drawable.ic_media_video_poster);
            }
            Glide.with(holder.picAlbum.getContext())
                    .load(bitmap)  // 直接加载 Bitmap
//                    .override(bitmap.getWidth(), bitmap.getHeight())  // 限制图片大小
//                    .placeholder(R.drawable.placeholder)  // 可选：加载占位图
//                    .error(R.drawable.error)  // 可选：加载失败时的图片
                    .into(holder.picAlbum);
            holder.picAlbum.setImageBitmap(bitmap);
            holder.picTypeImg.setVisibility(View.VISIBLE);
            holder.filePath=photofilename;
        }




    // 获取照片的拍摄时间

    //定义一个设置Listener的方法（），作用是暴露给外面的调用者，方便调用
    public void setOnRecyclerViewItemClickListener(onRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        mOnRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }
}

